<?php
namespace app\client\controller;

use think\swoole\facade\Task;

class DeliveryAddress extends Base {
    public function __construct() {
        parent::__construct();
    }
    
    
    public function index() {
        $address = model('DeliveryAddress')->findAll(['user_id' => $this->userid], ['id', 'province', 'city', 'district', 'address', 'consignee', 'mobile', 'is_default']);
        return successResult(['address' => $address]);
    }
    
    public function getAddressById (){
        $id = request()->get('id', 0, 'intval');
        if($id <= 0){
            return errorResult();
        }
        
        $address = model('DeliveryAddress')->findOne(['id' => $id], ['user_id', 'province', 'city', 'district', 'address', 'consignee', 'mobile', 'is_default']);
        if(empty($address) || $address['user_id'] != $this->userid){
            return errorResult();
        }else{
            unset($address['user_id']);
            return successResult(['address' => $address]);
        }
    }
    
    //获取默认地址
    public function getDefault () {
        $address = model('DeliveryAddress')->where(['user_id' => $this->userid])->order('is_default desc')->field(['id', 'province', 'city', 'district', 'consignee', 'mobile', 'address'])->find();
        if(empty($address)){
            return errorResult('无可用地址');
        }else{
            return successResult(['address' => $address]);
        }
    }
    
    public function save() {
        $params = request()->post();
        
        $id = isset($params['id']) ? intval($params['id']) : 0;
        if($id < 0){
            return errorResult();
        }
        
        $data = [];
        
        $data['consignee'] = isset($params['consignee']) ? trim(htmlspecialchars($params['consignee'])) : '';
        if($data['consignee'] === ''){
            return errorResult('请填写收货人');
        }
        
        $data['mobile'] = isset($params['mobile']) ? trim(htmlspecialchars($params['mobile'])) : '';
        if(!valiMobile($data['mobile'])){
            return errorResult('请填写正确的手机号码');
        }
        
        $data['province'] = isset($params['province']) ? trim(htmlspecialchars($params['province'])) : '';
        $data['city'] = isset($params['city']) ? trim(htmlspecialchars($params['city'])) : '';
        $data['district'] = isset($params['district']) ? trim(htmlspecialchars($params['district'])) : '';
        
        if($data['province'] === '' || $data['city'] === '' || $data['district'] === '') {
            return errorResult('请选择省市区');
        }
        
        $data['address'] = isset($params['address']) ? trim(htmlspecialchars($params['address'])) : '';
        if($data['address'] === ''){
            return errorResult('请填写详细地址');
        }
        
        /* $data['province_id'] = isset($params['province_id']) ? intval($params['province_id']) : 0;
        $data['city_id'] = isset($params['city_id']) ? intval($params['city_id']) : 0;
        $data['district_id'] = isset($params['district_id']) ? intval($params['district_id']) : 0;
        
        $areas = model('Area')->where(['id' => [$data['province_id'], $data['city_id'], $data['district_id']]])->field('name')->order('level')->select()->toArray();
        if(empty($areas) || count($areas) != 3){
            return errorResult('请选择地区');
            
            $data['province'] = $areas[0]['name'];
            $data['city'] = $areas[1]['name'];
            $data['district'] = $areas[2]['name'];
        } */
        
        $data['is_default'] = isset($params['is_default']) ? intval($params['is_default']) : 0;
        
        if(!in_array($data['is_default'], [0, 1])){
            return errorResult();   
        }
        
        $userId = $this->userid;
        
        $model = model('DeliveryAddress');
        
        if($id){ //编辑
            $fields = array_keys($data);
            array_push($fields, 'user_id');
            $address = $model->findOne(['id' => $id], $fields);
            if(!$address || $address['user_id'] != $userId){
                return errorResult('1');
            }
            
            $updateData = [];
            
            foreach($data as $k => $val) {
                if($address[$k] != $val){
                    $updateData[$k] = $val;
                }
            }
            
            if($updateData){
                $rs = $model->modify(['id' => $id], $updateData);
                if($rs === false){
                    return errorResult('2');
                }
                
                if(!empty($updateData['is_default'])){ //设为默认地址
                    Task::async(function() use($model, $id, $userId) {
                        $model->modify("id != {$id} and user_id = {$userId} and is_default = 1", ['is_default' => 0]);
                        return true;
                    });
                }
            }
            
            
            return successResult();
            
        }else{ //新增
            $count = $model->where(['user_id' => $this->userid])->count();
            if($count >= 10){
                return errorResult('最多十条收货地址');
            }
            
            if($count == 0){ //第一条为默认地址
                $data['is_default'] = 1;
            }
            
            $data['user_id'] = $userId;

            $id = $model->add($data);
            if(!$id){
                return errorResult();
            }
            
            if($data['is_default'] == 1 && $count > 0){
                Task::async(function() use($model, $userId, $id) {
                    $model->modify("id != {$id} and user_id = {$userId} and is_default = 1", ['is_default' => 0]);
                    return true;
                });
            }
            
            return successResult(['id' => $id]);
        }
        
    }
    
    
    //删除
    public function delete() {
        $id = request()->route('id', 0, 'intval');
        if($id <= 0){
            return errorResult();
        }
        
        $model = model('DeliveryAddress');
        
        $address = $model->findOne(['id' => $id], ['user_id', 'is_default']);
        
        if(!$address || $address['user_id'] != $this->userid){
            return errorResult();
        }
        
        $rs = $model->where(['id' => $id])->delete();
        if(!$rs){
            return errorResult();
        }
        
        if($address['is_default'] == 1){ //是默认地址
            $userId = $this->userid;
            Task::async(function() use($model, $userId) {
                $rs = $model->where(['user_id' => $userId])->field('id')->order('id desc')->find();
                if($rs){
                    $model->modify(['id' => $rs['id']], ['is_default' => 1]);
                }
                return true;
            });
        }
        
        return successResult();
    }
}



